#include "rts-thread.hh"

#include <math/vector.hh>

#include "server.hh"
#include "physic/fps-zone.hh"
#include "ai/ai_handler.hh"

RtsThread::RtsThread (Server* s,
		      const tbb::concurrent_hash_map<int, boost::shared_ptr<Client> >& cl,
		      ObjVect* objvect):
  GameThread (s, cl, objvect),
  s_ (s)
{
}

RtsThread::~RtsThread ()
{
}

void
RtsThread::run ()
{
  OctreeRts* oct = OctreeRts::Instance ();
  Physic phy = Physic (*objvect_);

  // uncomment if you want to disconnect the server after all clients are gone

  // bool toto = false;
  double current = SDL_GetTicks ();
  double elapsed = 0;
  double start = SDL_GetTicks ();

  //add a FPS zone
  FpsZone* fpszone = new FpsZone (Vector3f (30, 30, 3), Vector3d (0, 0, 0), Vector3f (2, 2, 2), s_);
  phy.add_zone (fpszone);
  s_->add_zone (fpszone);

  while (1)
  {
    if (s_->gm ()->is_winner ())
      {
	std::cout << "The winner is: " << s_->gm ()->winner () << std::endl;
	break;
      }
    boost::shared_ptr<Request> req;

    if (r_.try_pop (req))
      (*req) (&rh_);

    if (SDL_GetTicks () - start > 100)
      start = SDL_GetTicks ();

    elapsed = SDL_GetTicks () - current;
    current = SDL_GetTicks ();
    // if (nbclients_)
    //   toto = true;

    // if (toto && !nbclients_)
    //   break;
    if (elapsed >= Physic::TIMESTEP)
    {
      // FIXME: Uncomment to enable AI.
      //s_->gm ()->ai_handler ()->act ();
      phy.update (Physic::TIMESTEP);
      if (!phy.mov_obj ().empty ())
	send_physic_updates (phy.mov_obj ());
      elapsed -= Physic::TIMESTEP;
    }
  }

  delete oct;
}
